package com.example.sharding;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 斌~
 * @version 1.0
 * @date 2020/12/6 5:55 下午
 */
public class SNOWFLAKEShardingRule implements PreciseShardingAlgorithm<Long> {

    /**
     * @param collection 数据分片表 t_order_1 , t_order_1
     * @param preciseShardingValue 分片规则的字段
     * @return String
     */
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
        Long id = preciseShardingValue.getValue(); //id
//        int mod = Math.abs(id.hashCode()%collection.size()) ;
        long mod = Math.abs(id%collection.size()) ;
        List<String> collect = new ArrayList<>(collection);
        return collect.get(Math.toIntExact(mod));
    }
}
